import React, { useEffect, useState } from 'react';
import classNames from 'classnames';
import './login.css';
import { admin_title } from '../../../config/admin.config';
import { useRequest } from '@umijs/hooks';
import { history } from 'umi';
import { loginAjax } from '@/services/globalServices';
import { Button } from 'antd';
import { useModel } from '@@/plugin-model/useModel';

let login: any,
  login_brand: any,
  login_wrapper: any,
  login_login: any,
  login_wrapper_height: any,
  login_back_link: any,
  forgot_link: any,
  login_link: any,
  login_btn: any,
  register_link: any,
  password_group: any,
  password_group_height: any,
  login_register: any,
  login_footer: any,
  box: any,
  option: any;

export default () => {
  const [email, setEmail] = useState('');
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [emailError, setEmailError] = useState(false);
  const [usernameError, setUsernameError] = useState(false);
  const [passwordError, setPasswordError] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  const { loading, run } = useRequest(loginAjax, {
    manual: true,
    debounceInterval: 500,
    onSuccess: (result, params) => {
      sessionStorage.setItem('token', result.token);
      history.push('/');
    },
  });
  useEffect(() => {
    login = document.querySelector('.login');
    login_brand = document.querySelector('.login-brand');
    login_wrapper = document.querySelector('.login-wrapper');
    login_login = document.querySelector('.login-login');
    login_wrapper_height = 0;
    login_back_link = document.querySelector('.login-back-link');
    forgot_link = document.querySelector('.forgot-link');
    login_link = document.querySelector('.login-link');
    login_btn = document.querySelector('.login-btn');
    register_link = document.querySelector('.register-link');
    password_group = document.querySelector('.password-group');
    password_group_height = 0;
    login_register = document.querySelector('.login-register');
    login_footer = document.querySelector('.login-footer');
    box = document.getElementsByClassName('login-box');
    init({
      login_url: '#login',
      forgot_url: '#forgot',
    });
  }, []);

  const init = (o?: any) => {
    setHeight(box[0].offsetHeight + login_footer.offsetHeight);
    password_group.style.height = password_group.offsetHeight + 'px';
    password_group_height = password_group.offsetHeight;
    login_wrapper_height = login_wrapper.offsetHeight;
    option = o;
    let len = box.length - 1;
    for (let i = 0; i <= len; i++) {
      if (i !== 0) {
        box[i].className += ' login-flip';
      }
    }
  };

  const goRegister = (e: any) => {
    login_login.className += ' login-animated';
    setTimeout(() => {
      login_login.style.display = 'none';
    }, 500);
    login_register.style.display = 'block';
    login_register.className += ' login-animated-flip';
    setHeight(login_register.offsetHeight + login_footer.offsetHeight);
    e.preventDefault();
  };

  const goLogin = (e: any) => {
    login_register.classList.remove('login-animated-flip');
    login_register.className += ' login-animated-flipback';
    login_login.style.display = 'block';
    login_login.classList.remove('login-animated');
    login_login.className += ' login-animatedback';
    setTimeout(() => {
      login_register.style.display = 'none';
    }, 500);
    setTimeout(() => {
      login_register.classList.remove('login-animated-flipback');
      login_login.classList.remove('login-animatedback');
    }, 1000);
    setHeight(login_login.offsetHeight + login_footer.offsetHeight);
    e.preventDefault();
  };

  const setHeight = (height: number) => {
    login_wrapper.style.minHeight = height + 'px';
  };

  const forgot = (e: any) => {
    password_group.classList += ' login-animated';
    login_back_link.style.display = 'block';
    setTimeout(() => {
      login_back_link.style.opacity = 1;
      password_group.style.height = 0;
      password_group.style.margin = 0;
    }, 100);
    setTimeout(() => {
      password_group.style.display = 'none';
    }, 1000);
    login_btn.innerText = '找回密码';
    setHeight(login_wrapper_height - password_group_height);
    e.preventDefault();
  };

  const loginBack = (e: any) => {
    password_group.classList.remove('login-animated');
    password_group.classList += ' login-animated-back';
    password_group.style.display = 'block';
    setTimeout(() => {
      login_back_link.style.opacity = 0;
      password_group.style.height = password_group_height + 'px';
      password_group.style.marginBottom = 30 + 'px';
    }, 100);
    setTimeout(() => {
      login_back_link.style.display = 'none';
      password_group.classList.remove('login-animated-back');
    }, 1000);
    login_btn.innerText = '登录';
    setHeight(login_wrapper_height);
    e.preventDefault();
  };

  const brand = () => {
    login_brand.classList += ' login-animated';
    setTimeout(() => {
      login_brand.classList.remove('login-animated');
    }, 1000);
  };

  const resetState = () => {
    setEmail('');
    setPassword('');
    setUsername('');
    setPasswordError(false);
    setEmailError(false);
    setUsernameError(false);
    setErrorMessage('');
  };

  const formSubmit = () => {
    if (login_btn.innerText === '登 录') {
      loginSubmit();
    } else {
      forgotPasswordSubmit();
    }
  };

  const loginSubmit = () => {
    if (email === '') {
      setEmailError(true);
      setErrorMessage('请填写登录邮箱!');
      return;
    } else if (password === '') {
      setPasswordError(true);
      setErrorMessage('请填写登录密码!');
      return;
    }
    run({
      email,
      password,
    });
  };

  const forgotPasswordSubmit = () => {
    if (email === '') {
      setEmailError(true);
      setErrorMessage('请填写找回邮箱!');
      return;
    }
  };

  const registerSubmit = () => {
    if (username === '') {
      setUsernameError(true);
      setErrorMessage('请填写用户名!');
      return;
    } else if (email === '') {
      setEmailError(true);
      setErrorMessage('请填写登录邮箱!');
      return;
    } else if (password === '') {
      setPasswordError(true);
      setErrorMessage('请填写登录密码!');
      return;
    }
  };

  return (
    <div className="login">
      <div className="login-brand">
        <img src="https://s1.ax1x.com/2020/04/02/GJmDzj.jpg" alt="logo" />
      </div>
      <div className="login-wrapper">
        <div className="login-box login-login">
          <div className="login-box-inner">
            <div>
              <p>{admin_title}</p>
              <div className="login-group">
                <label>
                  邮箱:
                  {emailError && (
                    <span style={{ marginLeft: 8, color: '#ff4c50' }}>
                      {errorMessage}
                    </span>
                  )}
                  <a
                    className="login-back-link"
                    onClick={e => {
                      resetState();
                      loginBack(e);
                    }}
                  >
                    登录?
                  </a>
                </label>
                <input
                  value={email}
                  onFocus={() => {
                    setEmailError(false);
                    setErrorMessage('');
                  }}
                  onChange={e => {
                    setEmail(e.target.value);
                  }}
                  className={classNames(
                    'login-input',
                    emailError && 'login-input-error',
                  )}
                />
              </div>
              <div className="login-group password-group">
                <label>
                  密码:
                  {passwordError && (
                    <span style={{ marginLeft: 8, color: '#ff4c50' }}>
                      {errorMessage}
                    </span>
                  )}
                  <a
                    className="forgot-link"
                    onClick={e => {
                      resetState();
                      forgot(e);
                    }}
                  >
                    忘记密码?
                  </a>
                </label>
                <input
                  type="password"
                  value={password}
                  onChange={e => {
                    setPassword(e.target.value);
                  }}
                  onKeyDown={event => {
                    if (event.keyCode === 13) {
                      formSubmit();
                    }
                  }}
                  onFocus={() => {
                    setPasswordError(false);
                    setErrorMessage('');
                  }}
                  className={classNames(
                    'login-input',
                    passwordError && 'login-input-error',
                  )}
                />
              </div>
              <Button
                loading={loading}
                style={{ height: 'auto' }}
                onClick={formSubmit}
                className="login-btn"
              >
                登录
              </Button>
              <div className="text-foot">
                未注册账户?
                <a
                  className="register-link"
                  onClick={e => {
                    resetState();
                    brand();
                    goRegister(e);
                  }}
                >
                  去注册
                </a>
              </div>
            </div>
          </div>
        </div>
        <div className="login-box login-register">
          <div className="login-box-inner">
            <div>
              <p>创建您的账户</p>
              <div className="login-group">
                <label>
                  用户名:{' '}
                  {usernameError && (
                    <span style={{ marginLeft: 8, color: '#ff4c50' }}>
                      {errorMessage}
                    </span>
                  )}
                </label>
                <input
                  type="text"
                  value={username}
                  onChange={e => {
                    setUsername(e.target.value);
                  }}
                  onFocus={() => {
                    setUsernameError(false);
                    setErrorMessage('');
                  }}
                  className={classNames(
                    'login-input',
                    usernameError && 'login-input-error',
                  )}
                />
              </div>
              <div className="login-group">
                <label>
                  邮箱:{' '}
                  {emailError && (
                    <span style={{ marginLeft: 8, color: '#ff4c50' }}>
                      {errorMessage}
                    </span>
                  )}
                </label>
                <input
                  value={email}
                  onChange={e => {
                    setEmail(e.target.value);
                  }}
                  onFocus={() => {
                    setEmailError(false);
                    setErrorMessage('');
                  }}
                  className={classNames(
                    'login-input',
                    emailError && 'login-input-error',
                  )}
                />
              </div>
              <div className="login-group">
                <label>
                  密码:{' '}
                  {passwordError && (
                    <span style={{ marginLeft: 8, color: '#ff4c50' }}>
                      {errorMessage}
                    </span>
                  )}
                </label>
                <input
                  type="password"
                  value={password}
                  onChange={e => {
                    setPassword(e.target.value);
                  }}
                  onFocus={() => {
                    setPasswordError(false);
                    setErrorMessage('');
                  }}
                  className={classNames(
                    'login-input',
                    passwordError && 'login-input-error',
                  )}
                />
              </div>
              <button onClick={registerSubmit} className="login-btn">
                注册
              </button>
              <div className="text-foot">
                已拥有账户?
                <a
                  className="login-link"
                  onClick={e => {
                    resetState();
                    brand();
                    loginBack(e);
                    goLogin(e);
                  }}
                >
                  登录
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
      <footer className="login-footer" />
    </div>
  );
};
